package member.action;

import static common.utils.Constants.LIMIT;
import hotel.service.IHotelOrderService;
import hotel.service.IHotelReviewService;
import hotel.service.IRoomStyleService;

import java.net.InetAddress;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import member.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import common.action.BaseAction;
import common.pojo.HotelOrder;
import common.pojo.Member;
import common.pojo.MemberInfo;
import common.pojo.MemberOtherInfo;
import common.pojo.Review;
import common.utils.Constants;
import common.utils.MD5Util;
import common.utils.Page;
import common.utils.PageUtil;
import common.utils.PaginationUtil;

@SuppressWarnings("serial")
@Scope("prototype")
@Controller("memberFront")
public class MemberFrontAction extends BaseAction {

	@Autowired
	private IMemberService memberService;
	@Autowired
	private IHotelOrderService hotelOrderService;

	/**
	 * 验证登录
	 */
	public void memberlogin() throws Exception {
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		Member memb = memberService.findByName(name);
		if ((name == null) || (pwd == null) || (name == "") || (pwd == "")) {
			response.getWriter().write("{\"success\":false,\"msg\":0}");
		} else if (memb == null) {
			response.getWriter().write("{\"success\":false,\"msg\":1}");
		} else {
			if (!MD5Util.md5(pwd).equals(memb.getPassword())) {
				response.getWriter().write("{\"success\":false,\"msg\":2}");
			} else if (!memb.getState()) {
				response.getWriter().write("{\"success\":false,\"msg\":3}");
			} else {			
				session.setAttribute(Constants.MEMBERID, memb.getId());
				session.setAttribute(Constants.USERNAME, memb.getName());
				//更新登录时间和IP
				memberService.update(getIp(), memb.getId());
				MemberOtherInfo other = memberService.findOtherInfoById(memb.getId());
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				session.setAttribute(Constants.LASTLOGINTIME, df.format(other.getLastLoginTime()));
				response.getWriter().write("{\"success\":true}");
			}
		}
	}

	public void loginSuccess() throws Exception{
		String returnUrl=request.getParameter("returnUrl");
		String userUrl=URLDecoder.decode(returnUrl,"UTF-8");
		response.sendRedirect(userUrl);		
	}
	

	/**
	 * 欢迎页面注册
	 */
	public void reg() throws Exception {
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String email = request.getParameter("email");
		Member memb = memberService.findByName(name);
		if (memb != null) {			
			response.getWriter().write("{\"success\":false}");
		} else {
			regTransport(name,pwd,email);
			response.getWriter().write("{\"success\":true}");	
		}
	}
	/**
	 * 注册页面注册
	 * @throws Exception
	 */
	public void regUser() throws Exception {
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String email = request.getParameter("email");
		regTransport(name,pwd,email);
		response.sendRedirect("index.action");		
	}
	
	private void regTransport(String name,String pwd,String email) throws Exception {
		Member member = new Member();
		member.setName(name);
		member.setPassword(MD5Util.md5(pwd));
		member.setEmail(email);
		MemberOtherInfo other = new MemberOtherInfo();
		other.setLoginIp(getIp());
		other.setRegIp(getIp());
		int memberId = memberService.save(member, other);
		session.setAttribute(Constants.MEMBERID, memberId);
		session.setAttribute(Constants.USERNAME, name);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		session.setAttribute(Constants.LASTLOGINTIME, df.format(new Date()));		
	}

	public void checkUser() throws Exception{	
		String name=request.getParameter("name");
		Member memb = memberService.findByName(name);
		if (memb != null) {
			response.getWriter().write("{\"success\":false}");
		} else {
			response.getWriter().write("{\"success\":true}");
		}
	}
	
	private String getIp() throws Exception {
		InetAddress addr = InetAddress.getLocalHost();
		return addr.getHostAddress().toString();
	}

	/**
	 * 个人中心主页
	 */
	public String index() throws Exception {
		int memberId = (Integer) (session.getAttribute(Constants.MEMBERID));
		String where = "memberId=" + memberId;
		hotelCount = hotelOrderService.getCount(where);
		orderlist = hotelOrderService.findHotList(
				" where verify=1 and tradeStatus!=5 "," ", " top 4 ");
		return "index";
	}

	/**
	 * 获取会员信息
	 */
	public String findUser() {
		int memberId = (Integer) (session.getAttribute(Constants.MEMBERID));
		member = memberService.findMemberById(memberId);
		memberInfo = memberService.findInfoById(memberId);
		return "findUser";
	}

	/**
	 * 修改信息
	 * 
	 * @throws Exception
	 */
	public void editUser() throws Exception {
		try {
			memberService.update(member, memberInfo);
			response.getWriter().write("{\"success\":true}");
		} catch (Exception e) {
			response.getWriter().write("{\"success\":false}");
		}
	}

	/**
	 * 修改密码
	 */
	public void editPassword() throws Exception {
		int memberId = (Integer) (session.getAttribute(Constants.MEMBERID));
		String oldpwd = request.getParameter("oldpwd");
		String newpwd = request.getParameter("newpwd");
		Member mem = memberService.findMemberById(memberId);
		if (MD5Util.md5(oldpwd).equals(mem.getPassword())) {
			memberService.updatePwd(MD5Util.md5(newpwd), memberId);
			response.getWriter().write("{\"success\":true}");
		} else {
			response.getWriter().write("{\"success\":false}");
		}
	}

	/**
	 * 登出
	 */
	public String loginOut() {
		session.removeAttribute(Constants.USERNAME);
		return "loginOut";
	}

	/**
	 * 获取订单列表
	 */
	public String getOrderList() {
		String totalTmp = request.getParameter("total");
		String currentTmp = request.getParameter("current");
		int memberId = (Integer) session.getAttribute(Constants.MEMBERID);
		String where = " memberId=" + memberId;
		int total;
		int current;
		if (totalTmp == null)
			total = orderService.getCount(where);
		else
			total = Integer.valueOf(request.getParameter("total"));
		if(currentTmp==null) current =1;
		else current = Integer.valueOf(request.getParameter("current"));
		Page page = PageUtil.createPage(LIMIT, total, current);
		orderlist = orderService.find(page.getBeginIndex(), LIMIT, "orderTime desc",where);
	    pagination = PaginationUtil.getPaginationStyleTwo(page,
		"getOrderList.action");
		return "orderlist";
	}

	/**
	 * 获取订单详情
	 */
	public String orderDetail() {
		int id = Integer.parseInt(request.getParameter("id"));
		hotelOrder = orderService.findInfoById(id);
		hotelOrder.setPicUrl(roomService.findInfoById(hotelOrder.getRoomStyleId()).getPicUrl());
		return "orderDetail";
	}

	/**
	 * 取消订单
	 */
	public void cancelOrder() throws Exception{
		int id = Integer.parseInt(request.getParameter("id"));
		orderService.updateState(id, 5);
		response.getWriter().write("{\"success\":true}");
	}
	
	/**
	 * 跳转到支付页面
	 */
	public String toPay() {
		int id = Integer.parseInt(request.getParameter("id"));
		hotelOrder = orderService.findInfoById(id);
		return "toPay";
	}

	/**
	 * 判断是否支付
	 * @throws Exception
	 */
	public void checkOrder() throws Exception{
		int id=Integer.parseInt(request.getParameter("id"));
		int status = orderService.findInfoById(id).getTradeStatus();
		if(status==2){
			response.getWriter().write("{\"success\":false}");
		}else{
		response.getWriter().write("{\"success\":true}");
		}
	}
	
	/**
	 * 确认支付
	 */
	public String surePay() {
		int id = Integer.parseInt(request.getParameter("id"));
		hotelOrder = orderService.findInfoById(id);
		//判断订单是否支付
		if(hotelOrder.getTradeStatus()==2){
			isPay="您已经支付过了哦~";
		}else{			
			orderService.updateState(id, 2);
		}		
		return "surePay";
	}
	
	/**
	 * 判断是否点评
	 * @throws Exception
	 */
	public void checkReview() throws Exception{
		int id=Integer.parseInt(request.getParameter("id"));
		boolean isreview = orderService.findInfoById(id).getIsReview();
		if(isreview){
			response.getWriter().write("{\"success\":false}");
		}else{
		response.getWriter().write("{\"success\":true}");
		}
	}
	/**
	 * 确定点评
	 */
	public void sureReview() throws Exception{
		String userName = (String) session.getAttribute(Constants.USERNAME);
		int orderid = Integer.parseInt(request.getParameter("review.orderId"));
		orderService.updateReview(orderid);
		reviewService.save(orderid, review, userName);
		// 回跳到点评列表
		response.sendRedirect("reviewList.action");
	}

	/**
	 * 点评列表
	 */
	public String reviewList() {
		String totalTmp = request.getParameter("total");
		String currentTmp = request.getParameter("current");
		String userName = (String) session.getAttribute(Constants.USERNAME);
		String where = " where username='"+userName+"'";
		int total;
		int current;
		if (totalTmp == null)
			total = reviewService.getCount(where);
		else
			total = Integer.valueOf(request.getParameter("total"));
		if(currentTmp==null) current =1;
		else current = Integer.valueOf(request.getParameter("current"));
		Page page = PageUtil.createPage(LIMIT, total, current);
		reviewlist = reviewService.find(where, page.getBeginIndex(), LIMIT,"id desc");
		pagination = PaginationUtil.getPaginationStyleTwo(page,
		"reviewList.action");
		return "reviewList";
	}

	/**
	 * 点评详情
	 */
	public String findReview() {
		int id = Integer.parseInt(request.getParameter("id"));
		review = reviewService.find(id);
		return "reviewShow";
	}

	@Resource
	private IHotelOrderService orderService;
	@Resource
	private IHotelReviewService reviewService;
	@Resource
	private IRoomStyleService roomService;
	
	private int hotelCount;
	private List<HotelOrder> orderlist;
	private HotelOrder hotelOrder;
	private Review review;
	private List<Review> reviewlist;
	private Member member;
	private MemberInfo memberInfo;
	private String pagination;
	//是否支付
	private String isPay;
	

	public String getIsPay() {
		return isPay;
	}

	public void setIsPay(String isPay) {
		this.isPay = isPay;
	}

	public String getPagination() {
		return pagination;
	}

	public void setPagination(String pagination) {
		this.pagination = pagination;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public MemberInfo getMemberInfo() {
		return memberInfo;
	}

	public void setMemberInfo(MemberInfo memberInfo) {
		this.memberInfo = memberInfo;
	}

	public List<Review> getReviewlist() {
		return reviewlist;
	}

	public void setReviewlist(List<Review> reviewlist) {
		this.reviewlist = reviewlist;
	}

	public Review getReview() {
		return review;
	}

	public void setReview(Review review) {
		this.review = review;
	}

	public HotelOrder getHotelOrder() {
		return hotelOrder;
	}

	public void setHotelOrder(HotelOrder hotelOrder) {
		this.hotelOrder = hotelOrder;
	}

	public List<HotelOrder> getOrderlist() {
		return orderlist;
	}

	public void setOrderlist(List<HotelOrder> orderlist) {
		this.orderlist = orderlist;
	}

	public int getHotelCount() {
		return hotelCount;
	}

	public void setHotelCount(int hotelCount) {
		this.hotelCount = hotelCount;
	}
}